/** 
 * @Description: 文件描述
 * @Author: 程前
 * @Date: 2025-01-14 14:25:16
 * @LastEditors: 程前
 * @LastEditTime: 2025-02-25 15:07:51
 */
import { Viewer, Entity, Cartesian3, Color, Primitive, CallbackProperty, Cartographic, Math as CesiumMath, sampleTerrainMostDetailed } from "cesium";
import { useDrawRiver } from "./waterPrimitive";
import { getAssetsFile } from "@/utils";

interface AnalysisInstance {
    clear: () => void;
}

export interface FloodAnalysisOptions {
    viewer: Viewer;
    coordinates: Cartesian3[];
    color?: Color;
    speed?: number;
    waterImg?: string;
    onHeightChange?: (height: number) => void;
    onComplete?: () => void;
}

export class FloodAnalysis implements AnalysisInstance {
    private viewer: Viewer;
    private coordinates: Cartesian3[];
    private color: Color;
    private speed: number;
    private waterImg?: string;
    private onHeightChange?: (height: number) => void;
    private onComplete?: () => void;

    private minHeight: number = 0;
    private maxHeight: number = 0;
    private currentHeight: number = 0;
    private animationInterval: NodeJS.Timeout | null = null;
    private waterPrimitive: any = null;
    private isAnalyzing: boolean = false;

    constructor(options: FloodAnalysisOptions) {
        this.viewer = options.viewer;
        this.coordinates = options.coordinates;
        this.color = options.color ?? Color.fromBytes(64, 157, 253);
        this.speed = options.speed ?? 2.0;
        this.waterImg = options.waterImg ?? getAssetsFile("cesium/waterNormal-1.jpg");
        this.onHeightChange = options.onHeightChange;
        this.onComplete = options.onComplete;

        // 重置所有状态
        this.minHeight = 0;
        this.maxHeight = 0;
        this.currentHeight = 0;
        this.isAnalyzing = false;
        if (this.animationInterval) {
            clearInterval(this.animationInterval);
            this.animationInterval = null;
        }

        // 启用地形深度测试
        this.viewer.scene.globe.depthTestAgainstTerrain = true;

        // 计算高度范围并创建水面
        this.calculateHeightRange();
    }

    private calculateHeightRange(): void {
        // 重置高度值
        let minHeight = Number.MAX_VALUE;
        let maxHeight = Number.MIN_VALUE;
        this.currentHeight = 0;

        // 获取地形高度
        const positions: Cartographic[] = [];
        this.coordinates.forEach(position => {
            const cartographic = Cartographic.fromCartesian(position);
            if (isNaN(cartographic.longitude) || isNaN(cartographic.latitude) || isNaN(cartographic.height)) {
                return;
            }
            positions.push(cartographic);
        });

        // 检查是否有有效的位置
        if (positions.length === 0) {
            return;
        }

        // 使用 sampleTerrainMostDetailed 获取精确的地形高度
        sampleTerrainMostDetailed(this.viewer.terrainProvider, positions).then((updatedPositions) => {
            updatedPositions.forEach(position => {
                if (typeof position.height === 'number' && !isNaN(position.height)) {
                    minHeight = Math.min(minHeight, position.height);
                    maxHeight = Math.max(maxHeight, position.height);
                }
            });

            // 验证高度范围的有效性
            if (minHeight === Number.MAX_VALUE || maxHeight === Number.MIN_VALUE) {
                return;
            }

            this.minHeight = minHeight;
            this.maxHeight = maxHeight + 2;
            // 从地形最低点开始
            this.currentHeight = minHeight;

            console.log('Height Range:', { minHeight, maxHeight, currentHeight: this.currentHeight });

            // 创建水面
            if (this.waterPrimitive) {
                const primitiveCollection = this.viewer.scene.primitives;
                primitiveCollection.remove(this.waterPrimitive);
                this.waterPrimitive = null;
            }
            this.createWaterPrimitive();

            // 开始分析
            this.start();
        }).catch(error => {
        });
    }

    private createWaterPrimitive(): void {
        try {
            // 将Cartesian3坐标转换为经纬度数组
            const boundary: number[] = [];
            this.coordinates.forEach(coord => {
                const cartographic = Cartographic.fromCartesian(coord);
                if (isNaN(cartographic.longitude) || isNaN(cartographic.latitude)) {
                    return;
                }
                const lon = CesiumMath.toDegrees(cartographic.longitude);
                const lat = CesiumMath.toDegrees(cartographic.latitude);
                if (isNaN(lon) || isNaN(lat)) {
                    return;
                }
                boundary.push(lon);
                boundary.push(lat);
            });

            // 检查边界点是否足够
            if (boundary.length < 6) { // 至少需要3个点（6个数值）
                return;
            }

            // 创建水面
            this.waterPrimitive = useDrawRiver(this.viewer, boundary, this.waterImg, this.currentHeight);
        } catch (error) {
        }
    }

    public start(): void {
        if (this.isAnalyzing) return;
        this.isAnalyzing = true;

        if (this.animationInterval) {
            clearInterval(this.animationInterval);
        }

        this.animationInterval = setInterval(() => {
            this.currentHeight += this.speed / 60; // 假设60fps

            if (this.currentHeight >= this.maxHeight) {
                this.currentHeight = this.maxHeight;
                this.stop();
                this.onComplete && this.onComplete()
                return;
            }

            // 更新水面高度
            if (this.waterPrimitive) {
                this.waterPrimitive.extrudedHeight = this.currentHeight;
            }

            if (this.onHeightChange) {
                this.onHeightChange(this.currentHeight);
            }
        }, 16); // 约60fps
    }

    public pause(): void {
        if (this.animationInterval) {
            clearInterval(this.animationInterval);
            this.animationInterval = null;
        }
        this.isAnalyzing = false;
    }

    public resume(): void {
        if (!this.isAnalyzing) {
            this.start();
        }
    }

    public stop(): void {
        this.pause();
        if (this.onHeightChange) {
            this.onHeightChange(this.currentHeight);
        }
    }

    public clear(): void {
        this.stop();
        if (this.waterPrimitive) {
            // 调用水面代理对象的 destroy 方法清理所有资源
            this.waterPrimitive.destroy();
            this.waterPrimitive = null;
        }
        // 重置所有状态
        this.isAnalyzing = false;
        this.currentHeight = 0;
        this.minHeight = 0;
        this.maxHeight = 0;
        if (this.animationInterval) {
            clearInterval(this.animationInterval);
            this.animationInterval = null;
        }
    }

    public getCurrentHeight(): number {
        return this.currentHeight;
    }

    public isActive(): boolean {
        return this.isAnalyzing;
    }
}

